package com.qf.test;

import com.qf.utils.ESUtil;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;

/**
 * 复合查询
 */
public class BoolDemo {



    /*
    # 公司名称以中国开头并且费用大于5里
    # 运营商不是联通
    # 所属地区是北京或者武汉
     */
    @Test
    public void bool() throws IOException {
        //1. 创建指定的Request对象，并设置索引名称和doc_id
        SearchRequest request = new SearchRequest();
        request.indices("sms-logs-index");

        //2. 设置添加的数据给Request对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.prefixQuery("corpName","中国")).must(QueryBuilders.rangeQuery("fee").gte(5));
        boolQuery.mustNot(QueryBuilders.termQuery("operatorId",2));
        boolQuery.should(QueryBuilders.termQuery("province","北京")).should(QueryBuilders.termQuery("province","武汉"));
        boolQuery.minimumShouldMatch(1);
        sourceBuilder.query(boolQuery);

        request.source(sourceBuilder);

        //3. 通过连接对象将Request发送给ES，并接受Response
        SearchResponse resp = ESUtil.getClient().search(request, RequestOptions.DEFAULT);

        //4. 通过Response判断添加是否成功
        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

}
